package cn.xydpeng.springframework.beans.factory.support;

import cn.xydpeng.springframework.beans.factory.DisposableBean;
import cn.xydpeng.springframework.lang.Nullable;
import cn.xydpeng.springframework.util.ReflectionUtils;

import java.lang.reflect.Method;

/**
 * @author xydpeng
 * @version v1.0
 * @date: 2022/10/19
 * @description: 适配器模式,
 */
public class DisposableBeanAdapter implements DisposableBean {
    private final Object bean;
    private final String beanName;
    @Nullable
    private String[] destroyMethodNames;

    //TODO 还需实现 DestructionAwareBeanPostProcessor 扩展点
    public DisposableBeanAdapter(Object bean, String beanName, RootBeanDefinition mbd) {
        this.bean = bean;
        this.beanName = beanName;
        this.destroyMethodNames = mbd.getDestroyMethodNames();
    }

    @Override
    public void destroy() throws Exception {
        boolean isDisposableBean = bean instanceof DisposableBean;
        if (isDisposableBean) {
            ((DisposableBean) bean).destroy();
        }
        if (destroyMethodNames != null) {
            for (String destroyMethodName : destroyMethodNames) {
                //避免重复调用
                if(isDisposableBean && "destroy".equals(destroyMethodName)){
                    continue;
                }
                Method method = bean.getClass().getMethod(destroyMethodName);
                ReflectionUtils.makeAccessible(method);
                method.invoke(bean);
            }
        }
    }

}
